import React, { useEffect, useState } from 'react';
import { Box, Button, Divider, Table, Message, Dialog, Input } from '@alifd/next';
import styles from './ExtraProps.module.scss';

const ExtraProps = ({ item, store, ...props }) => {
  // const { dictTreeStore: store } = useStore();
  const [extras, setExtras] = useState([]);

  useEffect(() => {
    const map = item?.extras || {};
    setExtras(Object.keys(map).map((k) => { return { ...map[k], name: k }; }));
  }, [item]);

  function validate(obj) {
    if (!obj.name || !obj.value) {
      Message.error({ content: i18n.t('属性名称和属性值不能为空'), style: { marginTop: '40vh' } });
      return false;
    }
    return true;
  }

  function save() {
    const postData = { ...item, extras: Util.toMap(extras, 'name') };
    store.update(postData);
  }
  const changeRowData = (index, key, value) => {
    if (key === '') { // 取消
      if (index >= Object.keys(item?.extras || {}).length) {
        extras.splice(index, 1);
      } else {
        delete extras[index].edited;
      }
      setExtras([...extras]);
      return;
    }
    if (key === 'edited' && value === false) { // 保存
      if (!validate(extras[index])) return;
      delete extras[index].edited;
      save();
    } else {
      extras[index][key] = value;
      setExtras([...extras]);
    }
  };

  const deleteRow = (index) => {
    Dialog.confirm({
      content: `确定要删除：${extras[index].name} ?`,
      onOk: () => {
        extras.splice(index, 1);
        setExtras([...extras]);
        save();
      },
    });
  };

  const addRow = () => {
    setExtras([...extras, { edited: true }]);
  };

  const renderEditCell = (v, i, row, key) => {
    return row.edited ? <Input style={{ width: '100%' }} onChange={(value) => changeRowData(i, key, value)} value={v || ''} />
      : v;
  };

  return (
    <div>
      <Box direction="row" margin={[0, 0, 16, 0]}>
        <Button onClick={addRow} className={styles.Button} disabled={extras[extras.length - 1]?.edited === true} type="primary">{' '}新增</Button>
      </Box>
      <Table fixedHeader maxBodyHeight={380} dataSource={extras} hasBorder={false} className={styles.Table}>
        <Table.Column title="属性名称" cell={(v, i, row) => renderEditCell(v, i, row, 'name')} dataIndex="name" />
        <Table.Column title="显示标题" cell={(v, i, row) => renderEditCell(v, i, row, 'title')} dataIndex="title" />
        <Table.Column title="属性值" cell={(v, i, row) => renderEditCell(v, i, row, 'value')} dataIndex="value" />
        <Table.Column
          title="操作"
          width={150}
          cell={(v, i, row) => {
            if (row.edited) {
              return (
                <div>
                  <Button text type="primary" onClick={() => changeRowData(i, 'edited', false)}>保存</Button>
                  <Divider direction="ver" />
                  <Button text type="primary" onClick={() => changeRowData(i, '', '')}>取消</Button>
                </div>
              );
            }

            return (
              <div>
                <Button type="primary" onClick={() => changeRowData(i, 'edited', true)} text>编辑</Button>
                <Divider direction="ver" />
                <Button type="primary" text onClick={() => deleteRow(i)}>删除</Button>
                {i === (extras.length - 1) &&
                  <>
                    <Divider direction="ver" />
                    <Button onClick={addRow} type="primary" text>新增</Button>
                  </>}
              </div>
            );
          }}
        />
      </Table>
    </div>
  );
};

export default ExtraProps;
